<?php

namespace Lib;

use Slim\Slim;

class MyTwigExtension extends \Twig_Extension
{
    private $baseUrl;
    
    public function __construct()
    {
        $posIndex = false;
        $phpSelf = $_SERVER['PHP_SELF'];
        if (strpos($phpSelf, '/indexdev.php') !== false) {
            $posIndex = strpos($phpSelf, '/indexdev.php');
        } else if (strpos($phpSelf, '/index.php') !== false) {
            $posIndex = strpos($phpSelf, '/index.php');
        }
        
        if ($posIndex === false) {
            $app = Slim::getInstance();
            $this->baseUrl = $app->request->getRootUri();
        } else {
            $this->baseUrl = substr($phpSelf, 0, $posIndex);
        }
    }
    
    public function getName()
    {
        return 'mytwig';
    }

    public function getFunctions()
    {
        return array(
            new \Twig_SimpleFunction('js', array($this, 'js'), array('is_safe' => array('html'))),
            new \Twig_SimpleFunction('css', array($this, 'css'), array('is_safe' => array('html'))),
            new \Twig_SimpleFunction('imgsrc', array($this, 'imgsrc'), array('is_safe' => array('html'))),
            //new \Twig_SimpleFunction('cfg', array($this, 'cfg'), array('is_safe' => array('html'))),
        );
    }
    
    public function js($uri)
    {
        $baseUrl = $this->baseUrl;
        return '<script type="text/javascript" src="' . "$baseUrl/web/$uri" . '"></script>';
    }

    public function css($uri)
    {
        $baseUrl = $this->baseUrl;
        return '<link rel="stylesheet" href="' . "$baseUrl/web/$uri" . '" />';
    }
    
    public function imgsrc($uri)
    {
        $baseUrl = $this->baseUrl;
        return "$baseUrl/web/$uri";
    }
}
